<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Star;
use App\Models\User;
use App\Models\UserExtend;
use App\Services\User\GetStareCountService;
use App\Services\User\GetStaredCountService;
use Illuminate\Http\Request;
use YangJiSen\CacheUserProvider\CacheForget;

class UserController extends BaseController
{

    public $model = User::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $model = new $this->model;
        $input = $request->input();
        $gender = $request->input('gender');
        $tag_ids = $request->input('tag_ids');
        $arr_tag_id = explode(",", $tag_ids);
        $is_add_animal = $request->input('is_add_animal', -1);
        $is_official = $request->input('is_official', -1);
        $search = ['nickname' => '', 'id' => 0, 'start_at' => '', 'end_at' => '', 'is_black' => -1];
        $order_by_key = $request->input('order_by_key', 'id');
        $order_by_value = $request->input('order_by_value', 'desc');
        $is_virtual = $request->input('is_virtual', -1);
        if ($is_virtual == 1)
            $order_by_key = 'openid';

        $users = $model->apply($search, $input)
            ->when($gender, function ($q) use($gender) {
                $q->where('gender', $gender);
            })
            ->with(['user_tag' => function($q) {
                $q->select('user_tags.id', 'title');
            }])
            ->when(!empty($arr_tag_id[0]), function ($q) use($arr_tag_id) {
                $q->whereHas('user_tag', function ($qr) use($arr_tag_id) {
                    $qr->whereIn('user_tags.id', $arr_tag_id);
                });
            })
            ->when($is_virtual != -1, function ($q) use($is_virtual) {
                $q->where('is_virtual', $is_virtual);
            })
            ->when($is_add_animal != -1, function ($q) use($is_add_animal) {
                if ($is_add_animal)
                    $q->where('animal_count', '>', 0);
                else
                    $q->where('animal_count', '=', 0);
            })
            ->when($is_official != -1, function ($q) use($is_official) {
                $q->where('is_official', '=', $is_official);
            })
            ->with('extend')
            ->orderBy($order_by_key, $order_by_value)
            ->paginate(per_page());
        foreach ($users as &$user) {
            $user->stared_count = GetStaredCountService::handle($user->id);
            $user->star_count = GetStareCountService::handle($user->id, Star::TYPE_ARTICLE);
        }
        return $this->paginate($users);
    }

    public function setTag(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'tag_ids' => 'required',
        ]);
        $input = $request->input();
        $arr_id = explode(",", $input['ids']);
        $arr_tag_id = explode(",", $input['tag_ids']);
        foreach ($arr_id as $id) {
            $user = User::find($id);
            if (in_array(1, $arr_tag_id)) {
                //地域
                $user->is_official = 1;
            } else
                $user->is_official = 0;
            $user->save();
            $user->user_tag()->sync($arr_tag_id);
            CacheForget::CacheForget($user);
        }
        return $this->success([]);
    }

    public function info(Request $request)
    {
        $model = new $this->model;
        $table = $model->getTable();
        $this->validate($request, [
            'id' => 'required|exists:' . $table . ",id"
        ]);
        $id = \request("id");
        $info = $this->model::with(['user_tag' => function($q) {
            $q->select('user_tags.id', 'title');
        }])->find($id);
        $info->stared_count = GetStaredCountService::handle($id);
        $info->star_count = GetStareCountService::handle($id, Star::TYPE_ARTICLE);
        return $this->success($info);
    }

    public function black(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'action' => 'required',
        ]);
        $action = $request->input('action');
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $user = User::find($id);
            if ($user) {
                if ($action == 'add') {
                    $user->is_black = 1;
                    $user->black_at = date('Y-m-d', strtotime("+7 day"));
                } else {
                    $user->is_black = 0;
                    $user->black_at = null;
                }
                $user->save();
                CacheForget::CacheForget($user);
            }
        }
        return $this->success([]);
    }

    public function store(Request $request) {
        $input = $request->input();
        $id = \request("id");
        if ($id) {
            $info = $this->model::find($id);
            if (!$info) {
                return $this->failed('ID不存在');
            }
            $info->update($input);
        } else {
            $input['is_virtual'] = 1;
            $info = $this->model::create($input);
            $id = $info->id;
            UserExtend::create([
                'user_id' => $id
            ]);
            CacheForget::CacheForget($info);
        }
        return $this->success($id);
    }

    public function assignVirtual(Request $request) {
        $this->validate($request, [
            'id' => 'required',
        ]);
        $user_id = \request('user_id', 360);
        $id = \request('id');
        $assign_user = User::find($user_id);
        $cur_user = User::find($id);
        if (!$cur_user->is_virtual)
            return $this->failed('该用户不是虚拟用户');

        $cur_user->openid = $assign_user->openid;
        $cur_user->save();
        CacheForget::CacheForget($cur_user);
        return $this->success([]);
    }

    public function restoreVirtual(Request $request) {
        $this->validate($request, [
            'id' => 'required',
        ]);
        $id = \request('id');
        $user = User::find($id);
        $user->openid = '';
        $user->save();
        CacheForget::CacheForget($user);
        return $this->success([]);
    }

}

